package com.anxin.act.task.service;

import com.alibaba.fastjson.JSONObject;
import com.anxin.act.task.dao.ViewHiTaskDao;
import com.anxin.act.task.dao.ViewRuTaskDao;
import com.anxin.act.task.dao.WfPushLogDao;
import com.anxin.act.task.entity.ViewHiTask;
import com.anxin.act.task.entity.ViewRuTask;
import com.anxin.act.task.entity.WfPushLog;
import com.anxin.act.task.vo.TaskVo;
import com.anxin.act.utils.ActTaskUtils;
import com.anxin.act.utils.ActUtils;
import com.anxin.act.wfEntrustTask.service.WfEntrustTaskService;
import com.anxin.common.utils.LogUtils;
import com.anxin.common.utils.sys.UserUtils;
import com.anxin.framework.redis.MqProducer;
import com.anxin.framework.redis.RedisMq;
import com.anxin.framework.security.entity.SysTempToken;
import com.anxin.sys.system.entity.SysUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 待办对接
 */
@Service
@Transactional(readOnly = false)
public class ActDockingService implements RedisMq {

    @Autowired
    private WfPushLogService wfPushLogService;

    @Autowired
    private ViewHiTaskDao viewHiTaskDao;

    @Autowired
    private WfPushLogDao wfPushLogDao;

    @Autowired
    private ActDockingSendService actDockingSendService;

    @Autowired
    private ViewRuTaskDao viewRuTaskDao;

    @Autowired
    private MqProducer mqProducer;

    @Autowired
    private ActDockingDelTaskService actDockingDelTaskService;

    /**
     * 发送待办提醒
     *
     * @param viewRuTask
     * @param owner     用户ID
     */
    public SysTempToken sendTask(ViewRuTask viewRuTask, String owner) {
        SysTempToken sysTempToken = new SysTempToken();
        List<String> entrustUserNameList = ActTaskUtils.findBeEntrustUserName(owner);
        for (String assignee : entrustUserNameList) {
            sysTempToken = this.sendTask(viewRuTask, owner, assignee);
        }
        return sysTempToken;
    }

    /**
     * 发送待办提醒
     *
     * @param viewRuTask
     * @param ownerId     用户ID
     */
    public SysTempToken sendTask(ViewRuTask viewRuTask, String ownerId,String assignee) {
        String status = "SUCCESS";
        String message = null;

        LogUtils.info("发送待办提醒：" + ownerId + ":" + assignee);

        // 保存提醒发送日志
        SysUser sysUser = UserUtils.getUserByUserName(assignee);
        // ① 保存推送的待办信息
        LogUtils.info("① 保存推送的待办信息");
        wfPushLogService.sendTodoTask(viewRuTask, ownerId, sysUser.getId(), status, message);

        // 对接发送待办
        LogUtils.info("③ 推送统一待办");
        SysTempToken sysTempToken = actDockingSendService.sendTodoTask(viewRuTask, sysUser.getId(), sysUser.getUserName(),ownerId);

        return sysTempToken;

    }



    /**
     * 删除待办消息
     *
     * @param taskVo 任务对象
     */
    public void delTask(TaskVo taskVo) {
        JSONObject data = new JSONObject();
        data.put("taskId",taskVo.getId());
        data.put("actId",taskVo.getActId());
        data.put("assignee",taskVo.getViewRuTask().getAssignee());
        mqProducer.sendMessage(ActDockingDelTaskService.class,data.toJSONString());
    }

    /**
     * 终止流程时删除待办
     * @param actId 流程实例ID
     */
    public void delTaskByActId(String actId){
        WfPushLog wfPushLogQuery = new WfPushLog();
        wfPushLogQuery.setActId(actId);
        wfPushLogQuery.setPushType("TODO");
        wfPushLogQuery.setStatus("SUCCESS");
        List<WfPushLog> wfPushLogList = wfPushLogService.findList(wfPushLogQuery);
        for (WfPushLog wfPushLog : wfPushLogList) {
            SysUser user = UserUtils.getUser(wfPushLog.getActAssignee());
            // 删除待办发送记录
            actDockingDelTaskService.delTodoTask(wfPushLog.getActId(),wfPushLog.getTaskId(),user);
        }
    }

    /**
     * 删除之前推送的待办
     * @param taskId 待办ID
     * @param userId 审批人ID
     */
    public void delTodoTask(String taskId,String userId){
        SysUser user = UserUtils.getUser(userId);

        ViewHiTask viewHiTask = viewHiTaskDao.getById(taskId);
        //  删除待办发送记录
        actDockingDelTaskService.delTodoTask(viewHiTask.getActId(),viewHiTask.getId(),user);
    }






    /**
     * 对接删除已办信息
     * @param viewHiTask
     */
    public void delHiTask(ViewHiTask viewHiTask){
        SysUser user = UserUtils.getUserByUserName(viewHiTask.getAssignee());
        if (user != null){
            wfPushLogService.delHiTask(viewHiTask,user);
        }
    }

    /**
     * 删除待办消息
     *
     * @param taskId 任务ID
     * @param taskId 用户ID
     */
    public void delTaskByUserName(String taskId,String userName) {
        SysUser sysUser = UserUtils.getUserByUserName(userName);
        if(sysUser != null){
            List<WfPushLog> wfPushLogList = wfPushLogService.findListByActOwner(taskId, sysUser.getId());
            for (WfPushLog wfPushLog : wfPushLogList) {
                SysUser user = UserUtils.getUser(wfPushLog.getActAssignee());
                // 删除待办发送记录
                actDockingDelTaskService.delTodoTask(wfPushLog.getActId(),wfPushLog.getTaskId(),user);
            }
        }
    }

    /**
     * 根据ActId重新发送待办提醒
     * @param actId
     * @return
     */
    @Override
    @Transactional(readOnly = false)
    public boolean onMessage(String actId) {
        Map<String,WfPushLog> wfPushLogMap = new HashMap<>();
        Map<String,ViewRuTask> viewRuTaskMap = new HashMap<>();


        // 删除之前的待办
        List<WfPushLog> wfPushLogList = wfPushLogDao.findListByActId(actId);
        for (WfPushLog wfPushLog : wfPushLogList) {
            wfPushLogMap.put(wfPushLog.getTaskId() +"_"+ wfPushLog.getActAssignee(),wfPushLog);
        }


        // 发送新的待办
        List<ViewRuTask> viewRuTaskList = viewRuTaskDao.findListByActId(actId);
        for (ViewRuTask ruTask : viewRuTaskList) {
            SysUser sysUser = UserUtils.getUserByUserName(ruTask.getAssignee());
            if (sysUser != null && !"Y".equals(ruTask.getHang())){
                viewRuTaskMap.put(ruTask.getId() + "_" + sysUser.getId(),ruTask);
            }
        }

        // 删除待办
        for (WfPushLog wfPushLog : wfPushLogList) {
            if (viewRuTaskMap.get(wfPushLog.getTaskId() + "_" + wfPushLog.getActAssignee()) == null) {
                SysUser user = UserUtils.getUser(wfPushLog.getActAssignee());
                LogUtils.info("删除流程:" + user.getNickName());
                actDockingDelTaskService.delTodoTask(wfPushLog.getActId(),wfPushLog.getTaskId(), user);
            }
        }


        for (ViewRuTask ruTask : viewRuTaskList) {
            SysUser sysUser = UserUtils.getUserByUserName(ruTask.getAssignee());
            if (sysUser != null){
                if (wfPushLogMap.get(ruTask.getId()+ "_" + sysUser.getId()) == null) {
                    LogUtils.info("发送待办:" + sysUser.getNickName());
                    this.sendTask(ruTask, sysUser.getId());
                }
            }
        }

        return true;
    }
}
